package com.ithaima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ithaima.reggie.common.CustomException;
import com.ithaima.reggie.dto.SetmealDto;
import com.ithaima.reggie.entity.Setmeal;
import com.ithaima.reggie.entity.SetmealDish;
import com.ithaima.reggie.mapper.SetmealMapper;
import com.ithaima.reggie.service.SetmealDishService;
import com.ithaima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        // 保存套餐基本信息
        this.save(setmealDto);
        
        // 获取套餐菜品列表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        
        // 为每个套餐菜品设置套餐ID
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        
        // 批量保存套餐菜品关系
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐，同时删除套餐关联的菜品信息
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        // 构造查询条件，检查是否有套餐正在售卖中（status == 1）
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);           // 查询指定ID的套餐
        queryWrapper.eq(Setmeal::getStatus, 1);         // 状态为启用（售卖中）
        int count = this.count(queryWrapper);           // 统计符合条件的套餐数量

        // 如果存在正在售卖的套餐，则抛出自定义异常，禁止删除
        if (count > 0) {
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        // 删除套餐信息
        this.removeByIds(ids);

        // 删除套餐关联的菜品信息
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId, ids);  // 根据套餐ID删除关联菜品
        setmealDishService.remove(queryWrapper1);          // 执行删除操作

    }
}